package com.kylin.module.community.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

//import java.util.ResourceBundle;
//import java.util.Locale;
//import com.kylin.common.util.ShortResourceBundle;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
//import org.apache.struts.util.MessageResources;
import org.hibernate.criterion.Order;

import com.kylin.common.Constants;
import com.kylin.module.community.orm.Member;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.common.paginate.Paging;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;

import com.kylin.module.shop.orm.Product;
import com.kylin.module.user.business.UserBlogic;
import com.kylin.module.user.orm.User;

 
import com.kylin.module.community.business.MemberBlogic;
import com.kylin.module.community.business.SitemsgBlogic;
import com.kylin.module.community.forms.MemberForm;
import com.kylin.module.community.forms.PostForm;
import com.kylin.struts.BaseActionInterface;
import com.kylin.struts.BaseDispatchAction;

import com.kylin.common.dict.orm.Dict;
import com.kylin.common.entity.MsgKey;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.util.MemObjFactory;


public class MemberAction  extends BaseDispatchAction implements BaseActionInterface {

	protected static Logger log = Logger.getLogger(MemberAction.class);	
	
	public ActionForward unspecified(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("in member.unspecified");
		return this.add(mapping, actionForm, request, response);
	}

	public ActionForward save(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("in member.save");
		MemberForm form = (MemberForm)actionForm;
		log.info(form.toString());
		String forward = "home";
		try{
			form.setLanguage(getSessionLocale(request).toString());
			MemberBlogic bean = new MemberBlogic();
			
			if(form.getId().longValue()==0 || form.getId() ==null){ 
				Member member= bean.addMember(form); 
				String path = mapping.findForward("add").getPath();
				User user = member.getUser();
				if (user != null){
					request.getSession().setAttribute(Constants.CURR_USER, user);				
					//path = "/module/community/member/post.do?task=mypost&uid="+member.getUser().getId();
					path = "/module/community/member/addMemberSucc.jsp";
				}
				else{
					
				}
				log.info("path: "+path);
	
				ActionForward actionforward = new ActionForward(path);
				actionforward.setRedirect(true);
				return actionforward;			
			}
			else{				
				bean.updateMember(form);
			}
			log.info("保存用户信息："+ form.getUsername());
		}catch (Exception e) {
			forward = doException( request, e, "add");
		}
		///module/community/member/post.do?task=mypost&uid=58
		return mapping.findForward(forward);
	}

	public ActionForward search(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		return null;
	}	

	public ActionForward add(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
        log.info("in member.add");
		String forward ="add";
		Locale locale = getSessionLocale(request);//new Locale("zh","CN");
		List sysLangList = MemObjFactory.getSysLanguageList(locale);
		request.setAttribute("sysLangList",sysLangList);
		   
		List countryList = MemObjFactory.getAllCountryList(locale);
		request.setAttribute("countryList",countryList);
		
		//String language = "zh_CN";
		log.info("member.add locale: " + locale.toString());
		List interests = MemObjFactory.getDict("interest", locale.toString());
		request.setAttribute("interests", interests);
		
		return mapping.findForward(forward);
	}		

	
	public ActionForward delete(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		return null;
	}

	public ActionForward list(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("in member.list");
		String forward = "list";
		int pageNum = 1;
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				cinfo = new CriteriaInfo(Member.class, null, Order.asc("ordering"));		
				addUserCacheCriteriaInfo(request, cinfo);
			}else{
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			MemberBlogic bean = new MemberBlogic();
			DisplayPage page = bean.getMemberList(pageNum, cinfo);
			log.info("查询属性表 :" + page.getPageNumber());
			request.setAttribute("memberslist", page);
			
			/* begin userlist */
			/* ============================================== */
			int upageNum = 1;
			UserBlogic userbean= new UserBlogic();
			CriteriaInfo ucinfo = new CriteriaInfo(User.class, null, Order.asc("ordering"));		
			addUserCacheCriteriaInfo(request, ucinfo);			
			DisplayPage upage = userbean.getUserList(upageNum, ucinfo);
			request.setAttribute("userlist", upage);
			/* ============================================== */
			/* end user list */
			
			//Locale locale = new Locale("zh", "CN");			
			//ResourceBundle message = ResourceBundle.getBundle("message",locale);
			//
			///ShortResourceBundle message = new ShortResourceBundle("zh", "CN");
			//request.setAttribute("message", message);
			
		}catch (Exception e) {
			doException( request, e, "search");
		}
		return mapping.findForward(forward);
	}

	public ActionForward lastReg(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		
		log.info(" in member.lastReg");
		String forward = "lastReg";
		try {

			MemberBlogic bean = new MemberBlogic();
			List list = bean.getLastReg();
			//list.get(index)
			request.setAttribute(Constants.KEY_REQUEST_RESULT, list);	
			
		}catch (Exception e) {
			doException( request, e, "search");
		}
		return mapping.findForward(forward);
	}

 	
	public ActionForward edit(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info(" in member.edit ");
		int pageNum = 1;
		
		String forward ="edit";
		User user = null;
		if(request.getSession().getAttribute(Constants.CURR_USER)!= null){
		    user = (User)request.getSession().getAttribute(Constants.CURR_USER);
		}

		if (user != null){
			MemberBlogic bean = new MemberBlogic();	
			//HttpSession session =  request.getSession();
			Member member = null;
			Locale locale = getSessionLocale(request);// new Locale("zh","CN");
			try{
				member = bean.getMemberByUser(user);
			}
			catch(BusinessException e){
				doException( request, e, forward);
			}
			request.setAttribute("member", member);
			
			//ShortResourceBundle message = new ShortResourceBundle("zh", "CN");
			//request.setAttribute("message", message);
			try{
		    List sysLangList = MemObjFactory.getSysLanguageList(locale);
		    request.setAttribute("sysLangList",sysLangList);
		    
			String language = "zh_CN";
			List interests = MemObjFactory.getDict("interest", locale.toString());
			request.setAttribute("interests", interests);
			
		    List countryList = MemObjFactory.getAllCountryList(locale);
		    request.setAttribute("countryList",countryList);
			}
			catch(Exception e){
				log.info("exception in edit:"+ e.toString());
			}
		}
		else{
			//forward = "login";
		}
		return mapping.findForward(forward);
	}
	
	
	public ActionForward view(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info(" in member.view ");
		int pageNum = 1;

		String forward = "view";

		
		Long uid = new Long(request.getParameter("uid"));


		MemberBlogic bean = new MemberBlogic();	
		//HttpSession session =  request.getSession();
		Member member = null;
		Locale locale = getSessionLocale(request);// new Locale("zh","CN");
		try{
			member = bean.getMemberByUserId(uid);
		}
		catch(BusinessException e){
			doException( request, e, forward);
		}
		request.setAttribute(Constants.KEY_REQUEST_RESULT, member);
		
		//ShortResourceBundle message = new ShortResourceBundle("zh", "CN");
		//request.setAttribute("message", message);
		
		 List sysLangList = MemObjFactory.getSysLanguageList(locale);
		    request.setAttribute("sysLangList",sysLangList);
		    
		    List countryList = MemObjFactory.getAllCountryList(locale);
		    request.setAttribute("countryList",countryList);
		
		return mapping.findForward(forward);
	}

	
	public ActionForward info( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
        log.info(" in member.info ");
		String forward = "myinfo";
		String sid = request.getParameter("uid");
		Long uid = new Long(0L);
		if ( sid == "" || sid == null){
			log.info("no id ");
		}
		else{
			uid = new Long(request.getParameter("uid"));
		
			MemberBlogic bean = new MemberBlogic();	
			
			Member member = null;
			Locale locale = getSessionLocale(request);//new Locale("zh","CN");
			//locale.getLanguage();
			try{
				member = bean.getMemberByUserId(uid);
			}
			catch(BusinessException e){
				doException( request, e, "myinfo");
			}
			request.setAttribute("myinfo", member);
		}
		return mapping.findForward(forward);
	}		

	public ActionForward myinfo( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
        log.info(" in member.myinfo ");
		String forward = "myinfo";

		String sid = request.getParameter("uid");
		Long uid = new Long(0L);
		if ( sid == "" || sid == null){
		
		User user = null;		
		try{
		  if(request.getSession().getAttribute(Constants.CURR_USER)!= null){
			   user = (User)request.getSession().getAttribute(Constants.CURR_USER);
		  }
		  /*
		  else{
			  user = (User)BaseHibernateDAO.findById(User.class, new Long("15"));
			  request.getSession().setAttribute(Constants.CURR_USER, user); 
		  }
		  */
		}
		catch(Exception e){
			doException( request, e, "myinfo");			
		}
		MemberBlogic bean = new MemberBlogic();	
		
		Member member = null;
		Locale locale = getSessionLocale(request);//new Locale("zh","CN");
		if(user != null){
			uid = user.getId();
			try{
				member = bean.getMemberByUser(user);
			}
			catch(BusinessException e){
				doException( request, e, "myinfo");
			}
			request.setAttribute("myinfo", member);
		}
		
		 List sysLangList = MemObjFactory.getSysLanguageList(locale);
		 request.setAttribute("sysLangList",sysLangList);		 
		    
		 List countryList = MemObjFactory.getAllCountryList(locale);
		 request.setAttribute("countryList",countryList);
		}
		
		else{
			uid = new Long(request.getParameter("uid"));
		
			MemberBlogic bean = new MemberBlogic();	
			
			Member member = null;
			Locale locale = getSessionLocale(request);// new Locale("zh","CN");
			//locale.getLanguage();
			try{
				member = bean.getMemberByUserId(uid);
			}
			catch(BusinessException e){
				doException( request, e, "myinfo");
			}
			request.setAttribute("myinfo", member);
		}
		Integer newmsg = new Integer("0");
		SitemsgBlogic msgb = new SitemsgBlogic();
		if(msgb.getTotalUnread(uid)!=null){
			newmsg = msgb.getTotalUnread(uid);
		}
		request.setAttribute("newmsg", newmsg);
		return mapping.findForward(forward);
	}	
	
	public ActionForward show(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		
		String forward = "show";
		log.info("in member.show : " + actionForm.toString());
		
		int pageSize = 15;// 分页列表的每页行数  
		int pageNum = 1;  // 当前页号
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				List condsList = new LinkedList();
			//condsList.add(new PropertyCondition("active", Constants.ACTIVE_ON,PropertyCondition.OPERATOR_EQ ));
				if( hasParam(request.getParameter("username")) ){
					String likeExp = "%"+request.getParameter("username")+"%";
					condsList.add(new PropertyCondition("user.username",likeExp,PropertyCondition.OPERATOR_LIKE));
				}
				if( hasParam(request.getParameter("sex")) ){
					condsList.add(new PropertyCondition("sex",new Short(request.getParameter("sex")),PropertyCondition.OPERATOR_EQ));
				}
				if( hasParam(request.getParameter("country")) ){
					String country = request.getParameter("country");
					condsList.add(new PropertyCondition("country",country,PropertyCondition.OPERATOR_EQ));
				}
			    if( hasParam(request.getParameter("interest"))){
				    condsList.add(new PropertyCondition("interest.id",new Long(request.getParameter("interest")),PropertyCondition.OPERATOR_EQ ));
			    }
			    if( hasParam(request.getParameter("language"))){
				    condsList.add(new PropertyCondition("language",request.getParameter("language"),PropertyCondition.OPERATOR_EQ ));
			    }
			    if( hasParam(request.getParameter("targetlang"))){
				    condsList.add(new PropertyCondition("targetlang",request.getParameter("targetlang"),PropertyCondition.OPERATOR_EQ ));
			    }
				
				PropertyCondition[] array = (PropertyCondition[])condsList.toArray(new PropertyCondition[0]);
				// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
				cinfo = new CriteriaInfo(Member.class, array, Order.desc("lastupdatedon"));
				searchId = this.addUserCacheCriteriaInfo(request, cinfo);
				request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
			}
			cinfo = getUserCacheCriteriaInfo(request, searchId);
			if(cinfo == null)
				throw new BusinessException("长时间未刷新页面，上次查询已失效，请重新访问上个页面");
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute("members", page);			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		
/**		
		MemberForm form = (MemberForm)actionForm;
		
		Integer limitstart = new Integer("0");
		Integer limit = new Integer("10");
		if(request.getParameter("limitstart") != null )	{		
			limitstart = new Integer (request.getParameter("limitstart"));
		}	
		if(request.getParameter("limit") != null ){
			limit = new Integer (request.getParameter("limit"));
		}
		
		
		try {

			MemberBlogic bean = new MemberBlogic();			
			Paging page = bean.show(form, limitstart, limit);	
			//request.setAttribute("uid", uid);	
			request.setAttribute("members", page);			
		
		}catch (Exception e) {
			doException( request, e, forward);
		}
		**/
		return mapping.findForward(forward);
	}		
	
	/*
	 * 
	 *   
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward update(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		//String forward = "home";
		String forward = "message";
		log.info("in member.update" + actionForm.toString());
		log.info("forward id:"+((MemberForm)actionForm).getId());
		//log.info("查询属性表 :"+ ((MemberForm)actionForm).toString() );
		MemberBlogic bean = new MemberBlogic();	
		try{
			bean.updateMember((MemberForm)actionForm);
			
			Locale locale = getSessionLocale(request);//(Locale) session.getAttribute(Action.LOCALE_KEY);
			ActionMessages messages = new ActionMessages();
			String msg =  new MsgKey("community.message","用户信息已更新!").toString();
			messages.add("msg", new ActionMessage( msg ) );			
			saveMessages(request, messages);

		}catch (Exception e) {
			log.info("forward exception:"+e.toString() );
			forward = doException( request, e, "update");
		}
		
		return mapping.findForward(forward);
	}
	
	public ActionForward changePassword(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		String forward = "message";
		UserBlogic blogic = new UserBlogic();
		log.info(request.getParameter("userId") + " " +request.getParameter("oldPassword") + " " + request.getParameter("newPassword"));
		try {
			blogic.changePassword(request.getParameter("userId"), request.getParameter("oldPassword"), request.getParameter("newPassword"));
			log.debug("密码已修改" );
			ActionMessages messages = new ActionMessages();
			String msg =  new MsgKey("community.message","密码已修改!").toString();
			messages.add("msg", new ActionMessage( msg ) );			
			saveMessages(request, messages);			
			// 返回成功的显示信息，需要在结果页面添加 <mytag:MyActionMsg />
	        //request.setAttribute(Constants.MSGKEY, new MsgKey("","密码已修改"));
		}catch (Exception e) {
			forward = doException( request, e, forward);
		}
		//  /module/community/member/post.do?task=mypost
		
		/*
		String path = null;//	mapping.findForward("succ").getPath();
		path = "/module/community/member/post.do?task=mypost";
		log.info("path: "+path);

		ActionForward actionforward = new ActionForward(path);
		actionforward.setRedirect(true);
		return actionforward;	
		
	
		*/
		/*
		ActionMessages messages = new ActionMessages();
		messages.add("msg", new ActionMessage("修改密码成功"));			
		saveMessages(request, messages);		
		*/
		return mapping.findForward(forward);
		
	}
}


